//导入处理文件上传
const multer = require('multer')
// 配置文件上传中间件，指定上传文件的目录
const upload = multer({ dest: 'uploads/' }).single('file');
//导入解析xlsx文件
const xlsx = require('xlsx')
const moment = require('moment');
//导入题库,标签，科目,题库标签关联表的数据模型
const { T_exam_question } = require('../models/t_exam_question')
const { T_exam_label } = require('../models/t_exam_label')
const { T_subjects } = require('../models/t_exam_subjects')
const { T_exam_questions_and_label } = require('../models/t_exam_questions_and_label')
const { T_exam_paper_to_question } = require('../models/t_exam_paper')

//根据科目id来获取该科目所有题目的业务处理
exports.getAllT_question = async (req, res) => {
  try {
    const id = req.query.subId;

    // 检查subId是否存在
    const subject = await T_subjects.findByPk(id);
    if (!subject) {
      return res.status(404).json({
        code: 404,
        msg: '科目不存在',
      });
    }

    const t_question = await T_exam_question.findAll({
      where: {
        sub_id: id,
      },
    });

    // console.log(t_question);
    res.json({
      code: 200,
      msg: '查询全部成功',
      data: t_question,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      msg: error.message,
    });
  }
};

//通过id来查询题库中的题目信息
exports.getT_questionById = async (req, res) => {
  const { id } = req.params;
  console.log('ID is:', id);

  try {
    const t_question = await T_exam_question.findByPk(id);//根据id查询
    if (t_question) {
      res.json({
        "code": 200,
        "msg": "查询成功",
        "data": t_question,
      });
    } else {
      res.json({
        "code": 404,
        "mag": "查询失败,该题库中的题目id不存在",
      })
    };
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message
    });
  }
};

//通过id来查询答案信息
exports.getT_answerById = async (req, res) => {
  const { id } = req.params;
  console.log('ID is:', id);

  try {
    const t_question = await T_exam_question.findByPk(id);//根据id查询
    if (t_question) {
      const answer = t_question.answer
      res.json({
        "code": 200,
        "msg": "查询成功",
        "data": answer,
      });
    } else {
      res.json({
        "code": 404,
        "mag": "查询失败,该题库中的题目答案不存在",
      })
    };
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message
    });
  }
};

//更新题库中的题目信息
exports.updatet_question = async (req, res) => {
  const { id } = req.params; // 从URL参数中获取题目ID
  const { questionContent, type, score, options, difficulty, answer, label, subject } = req.body;

  try {
    const t_question = await T_exam_question.findByPk(id);
    if (!t_question) {
      res.json({
        code: 404,
        msg: '更新失败，该题目id不存在',
      });
    } else {
      const t_subject = await T_subjects.findOne({ where: { subject } });
      if (!t_subject) {
        res.json({
          code: 400,
          msg: '科目不存在',
        });
      } else {
        // 更新题目的相关信息
        t_question.questionContent = questionContent;
        t_question.type = type;
        t_question.options = options;
        t_question.score = score;
        t_question.difficulty = difficulty;
        t_question.answer = answer;
        t_question.label = label;
        t_question.sub_id = t_subject.id;

        await t_question.save(); // 保存更新后的题目信息

        // 清空该题目原有的标签关联
        await T_exam_questions_and_label.destroy({ where: { question_id: id } });

        // 解析标签信息，获取标签ID并更新题目关联的标签
        for (const labelName of label) {
          const t_tag = await T_exam_label.findOne({ where: { label: labelName } });
          if (t_tag) {
            // 将题目和标签的关联信息存储到题目标签表中
            await T_exam_questions_and_label.create({
              question_id: id,
              label_id: t_tag.id
            });
          }
        }

        res.json({
          code: 200,
          msg: '更新成功',
          data: t_question,
        });
      }
    }
  } catch (error) {
    res.json({
      code: 500,
      msg: error.message,
    });
  }
};

//添加题目
exports.createt_question = async (req, res) => {
  const { questionContent, type, score, options, difficulty, answer, label, subject } = req.body;
  try {
    const t_subject = await T_subjects.findOne({ where: { subject } });
    if (!t_subject) {
      res.json({
        code: 400,
        msg: '科目不存在',
      });
    } else {
      // 查询题目是否已存在
      const existingQuestion = await T_exam_question.findOne({ where: { questionContent } });
      if (existingQuestion) {
        res.json({
          code: 400,
          msg: '题目已存在',
        });
      } else {
        // 创建题目并关联科目
        const t_question = await T_exam_question.create({
          questionContent, type, score, options, difficulty, answer, label,
          sub_id: t_subject.id, // 设置题目的科目外键字段为已存在科目的id
        });

        // 获取插入的题目的ID
        const questionId = t_question.id;

        // 解析标签信息，获取标签ID并与题目ID关联存储到另一个表中
        for (const labelName of label) {
          const t_tag = await T_exam_label.findOne({ where: { label: labelName } });
          if (t_tag) {
            await T_exam_questions_and_label.create({
              question_id: questionId,
              label_id: t_tag.id
            });
          }
        }
        res.json({
          code: 200,
          msg: '创建成功',
          data: t_question,
        });
      }
    }
  } catch (error) {
    res.json({
      code: 500,
      msg: error.message,
    });
  }
};

// 删除题目
exports.deleteT_questionById = async (req, res) => {
  const { id } = req.params;
  try {
    // 检查该题目是否存在于试卷中
    const questionInPaper = await T_exam_paper_to_question.findOne({ where: { question_id: id } });
    if (questionInPaper) {
      // 如果存在于试卷中, 返回错误信息
      res.json({
        "code": 403,
        "msg": '该题目已存在试卷中, 不能删除',
      });
    } else {
      // 删除题目标签表中与该题目相关联的数据
      await T_exam_questions_and_label.destroy({ where: { question_id: id } });

      // 删除题库中的题目
      const deletedRows = await T_exam_question.destroy({
        where: { id },
      });
      if (deletedRows > 0) {
        res.json({
          "code": 200,
          "msg": '删除成功',
        });
      } else {
        res.json({
          "code": 404,
          "msg": `题库中的题目ID为${id}的记录不存在`,
        });
      }
    }
  } catch (error) {
    res.json({
      "code": 500,
      "msg": error.message,
    });
  }
};

//批量导入模块
// 批量导入模块
// exports.batchImport = async (req, res) => {
//   try {
//     upload(req, res, async (err) => {
//       if (err) {
//         return res.status(400).json({ success: 111, message: '文件上传失败', error: err.message });
//       }

//       const tikunPath = req.file.path; // 获取用户上传的文件路径
//       console.log(tikunPath);
//       // 使用 xlsx 库解析 xlsx 文件内容
//       const workbook = xlsx.readFile(tikunPath);
//       const worksheet = workbook.Sheets[workbook.SheetNames[0]];
//       const questions = xlsx.utils.sheet_to_json(worksheet);

//       // 将解析得到的题目数据插入到数据库表中
//       const insertedQuestions = await Promise.all(
//         questions.map(async ({ questionContent, type, options,  difficulty, answer, label, subject }) => {
//           // 检查题目表中是否已存在相同内容的题目
//           const existingQuestion = await T_exam_question.findOne({ where: { questionContent } });
//           if (existingQuestion) {
//             return null; // 如果已存在相同内容的题目，则跳过该题目
//           }

//           const t_subject = await T_subjects.findOne({ where: { subject } });
//           if (!t_subject) {
//             return null; // 如果找不到对应的科目，则跳过该题目
//           }

//           // 解析标签信息
//           const labelArray = label.split(","); // 将标签字符串按逗号分隔成数组

//           const optionsArray = options.split('\n').map(option => option.substring(2).trim());

//           console.log(optionsArray); // 输出 ["A. 选项a", "B. 选项b", "C. 选项c", "D. 选项d"]
//           console.log(typeof options, options);
//           console.log(typeof optionsArray, optionsArray);
//           const insertedQuestion = await T_exam_question.create({
//             questionContent,
//             type,
//             options: optionsArray,

//             difficulty,
//             answer,
//             sub_id: t_subject.id, // 设置题目的科目外键字段为已存在科目的id
//             label: labelArray, // 将标签数组直接存储到题目的标签字段中
//           });

//           // 解析标签ID并与题目ID一一对应存储到题目标签表中
//           await Promise.all(
//             labelArray.map(async (labelItem) => {
//               const t_tag = await T_exam_label.findOne({ where: { label: labelItem } });
//               if (t_tag) {
//                 await T_exam_questions_and_label.create({
//                   question_id: insertedQuestion.id,
//                   label_id: t_tag.id,
//                 });
//               }
//             })
//           );

//           // 返回成功插入的题目对象
//           return insertedQuestion;
//         })
//       );

//       // 过滤掉未成功插入的题目和重复的题目
//       const successQuestions = insertedQuestions.filter((question) => question !== null);

//       // 返回成功消息
//       res.json({ success: true, message: '文件上传成功.', data: successQuestions });
//     })
//   } catch (error) {
//     console.error(error);
//     res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
//   }
// };
const { sequelize } = require('../utill/getSequelize')

exports.batchImport = async (req, res) => {
  try {
    await upload(req, res, async (err) => {
      if (err) {
        return res.status(400).json({ success: false, message: '文件上传失败1', error: err.message });
      }

      const tikunPath = req.file.path; // 获取用户上传的文件路径

      try {
        const workbook = xlsx.readFile(tikunPath);
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const questions = xlsx.utils.sheet_to_json(worksheet, { range: 2 });

        // 使用数据库事务来确保题目数据的一致性
        const insertedQuestions = await sequelize.transaction(async (t) => {
          return await Promise.all(
            questions.map(async ({ questionContent, type, score, options, difficulty, answer, label, subject }) => {
              // 检查题目表中是否已存在相同内容的题目
              const existingQuestion = await T_exam_question.findOne({ where: { questionContent } });
              if (existingQuestion) {
                return null; // 如果已存在相同内容的题目,则跳过该题目
              }

              // 检查必填字段是否为空
              if (!questionContent || !type || !difficulty || !answer || !subject) {
                throw new Error(`题目内容、题目类型、难度、答案或科目不能为空`);
              }

              const t_subject = await T_subjects.findOne({ where: { subject } });
              if (!t_subject) {
                throw new Error(`找不到对应的科目`);
              }

              // 解析标签信息
              const labelArray = label.split(","); // 将标签字符串按逗号分隔成数组

              const optionsArray = options.split('\n').map(option => option.substring(2).trim());

              const insertedQuestion = await T_exam_question.create({
                questionContent,
                type,
                options: optionsArray,
                difficulty,
                score,
                answer,
                sub_id: t_subject.id, // 设置题目的科目外键字段为已存在科目的id
                label: labelArray, // 将标签数组直接存储到题目的标签字段中
              }, { transaction: t });

              // 解析标签ID并与题目ID一一对应存储到题目标签表中
              await Promise.all(
                labelArray.map(async (labelItem) => {
                  const t_tag = await T_exam_label.findOne({ where: { label: labelItem } });
                  if (t_tag) {
                    await T_exam_questions_and_label.create({
                      question_id: insertedQuestion.id,
                      label_id: t_tag.id,
                    }, { transaction: t });
                  }
                })
              );

              // 返回成功插入的题目对象
              return insertedQuestion;
            })
          );
        });

        // 过滤掉未成功插入的题目和重复的题目
        const successQuestions = insertedQuestions.filter((question) => question !== null);

        // 返回成功消息
        res.json({ success: true, message: '文件上传成功.', data: successQuestions });
      } catch (error) {
        console.error(error);
        res.json({
          code: 203,
          msg: "文件上传失败,请检查文件内容格式是否正确"
        });
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ success: false, message: '文件上传失败3', error: error.message });
  }
};

//通过科目来获取科目的信息
exports.
  getT_questionBySubject = async (req, res) => {
    const { subject } = req.query.subId; // 将变量名改为 subjectName
    console.log(subject);
    try {
      const subjectName = await T_subjects.findOne({
        where: { subject: subject } // 使用 subjectName 获取科目名称
      });

      if (subjectName) {
        const t_questions = await T_exam_question.findAll({
          where: { sub_id: subjectName.id },
          include: [
            {
              model: T_exam_label,
              include: [T_subjects]
            }
          ]
        });

        if (t_questions.length > 0) {
          res.json({
            code: 200,
            msg: '查询成功',
            data: t_questions
          });
        } else {
          res.json({
            code: 404,
            mag: '查询失败，该科目下没有题目'
          });
        }
      } else {
        res.json({
          code: 404,
          mag: '查询失败，该科目不存在'
        });
      }
    } catch (error) {
      res.json({
        code: 500,
        msg: error.message
      });
    }
  };

//题库中的题型统计
exports.getnumQuestionType = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据题型进行统计
    const typeCounts = questions.reduce((acc, question) => {
      acc[question.type] = (acc[question.type] || 0) + 1;
      return acc;
    }, {});

    // 将统计结果转换成所需的格式
    const formattedData = Object.keys(typeCounts).map(question_type => ({
      question_type,
      total_num: typeCounts[question_type].toString()
    }));

    res.json({
      code: 200,
      msg: '查询成功',
      data: formattedData
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

//题库中的题型难度统计
exports.getdifficultyQuestionType = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据难度进行统计
    const typeCounts = questions.reduce((acc, question) => {
      acc[question.difficulty] = (acc[question.difficulty] || 0) + 1;
      return acc;
    }, {});

    // 将统计结果转换成所需的格式
    const formattedData = Object.keys(typeCounts).map(difficulty => ({
      difficulty,
      total_num: typeCounts[difficulty].toString()
    }));

    res.json({
      code: 200,
      msg: '查询成功',
      data: formattedData
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

//题库中的题型标签统计
exports.getlabelQuestionType = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据题型进行统计
    const typeCounts = questions.reduce((acc, question) => {
      acc[question.label] = (acc[question.label] || 0) + 1;
      return acc;
    }, {});

    // 将统计结果转换成所需的格式
    const formattedData = Object.keys(typeCounts).map(question_type => ({
      question_type,
      total_num: typeCounts[question_type].toString()
    }));

    res.json({
      code: 200,
      msg: '查询成功',
      data: formattedData
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

//创建时间统计
exports.getcreatedAtQuestionType = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据创建时间年月进行统计
    const monthYearCounts = questions.reduce((acc, question) => {
      const createdAt = new Date(question.createdAt);
      const monthYear = `${createdAt.getFullYear()}-${createdAt.getMonth() + 1}`;
      acc[monthYear] = (acc[monthYear] || 0) + 1;
      return acc;
    }, {});

    // 将统计结果转换成所需的格式
    const formattedData = Object.keys(monthYearCounts).map(date => ({
      created_at: date,
      total_num: monthYearCounts[date].toString()
    }));

    res.json({
      code: 200,
      msg: '查询成功',
      data: formattedData
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

//题型知识点
exports.getlabelQuestionType1 = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据题型进行分类
    const typeQuestions = questions.reduce((acc, question) => {
      if (!acc[question.type]) {
        acc[question.type] = [];
      }
      acc[question.type].push(question);
      return acc;
    }, {});

    // 统计每个题型下不同的标签
    const typeLabels = Object.keys(typeQuestions).map(type => {
      const labels = [];
      typeQuestions[type].forEach(question => {
        if (!labels.includes(question.label)) {
          labels.push(question.label);
        }
      });
      return {
        question_type: type,
        labels: [...new Set(labels.flat())]
      };
    });

    res.json({
      code: 200,
      msg: '查询成功',
      data: typeLabels
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

//难度知识点
exports.getlabelQuestiondifficulty = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据题型进行分类
    const typeQuestions = questions.reduce((acc, question) => {
      if (!acc[question.difficulty]) {
        acc[question.difficulty] = [];
      }
      acc[question.difficulty].push(question);
      return acc;
    }, {});

    // 统计每个题型下不同的标签
    const typeLabels = Object.keys(typeQuestions).map(difficulty => {
      const labels = [];
      typeQuestions[difficulty].forEach(question => {
        if (!labels.includes(question.label)) {
          labels.push(question.label);
        }
      });
      return {
        question_difficulty: difficulty,
        labels: [...new Set(labels.flat())]
      };
    });

    res.json({
      code: 200,
      msg: '查询成功',
      data: typeLabels
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

exports.getlabelQuestiondifficulty1 = async (req, res) => {
  const { subid } = req.query;

  try {
    const questions = await T_exam_question.findAll({
      where: {
        sub_id: subid
      }
    });

    // 根据题型进行分类
    const typeQuestions = questions.reduce((acc, question) => {
      if (!acc[question.type]) {
        acc[question.type] = [];
      }
      acc[question.type].push(question);
      return acc;
    }, {});

    // 统计每个题型下不同的标签和数量
    const typeLabels = Object.keys(typeQuestions).map(type => {
      const labels = {};
      typeQuestions[type].forEach(question => {
        if (!labels[question.difficulty]) {
          labels[question.difficulty] = 0;
        }
        labels[question.difficulty]++;
      });
      return {
        question_type: type,
        labels: Object.entries(labels).map(([difficulty, count]) => ({ difficulty, count }))
      };
    });

    res.json({
      code: 200,
      msg: '查询成功',
      data: typeLabels
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Internal server error' });
  }
};